//
//  HTRefreshControl.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/24.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit

let HTRefreshControlH : CGFloat = 50
enum htRefreshControlState : Int {

    case Noraml = 0 //"默认"
    case pulling =  1//"松手时刷新"
    case Refreshing = 2//"刷新中"
    
}



class HTRefreshControl: UIControl {
    
//    var htState : htRefreshControlState?
    
    var htState : htRefreshControlState = .Noraml {
    
        didSet{
        
            switch htState {
            
            case .pulling:
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arroeImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                contentLable.text = "松手有奖金"
            case .Refreshing:
                self.arroeImage.hidden = true
                
                self.indecatorView.startAnimating()

                contentLable.text = "正在送你奖金"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + HTRefreshControlH
                })
                
                
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
                
            case .Noraml:
                self.indecatorView.stopAnimating()
                
                self.arroeImage.hidden = false
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arroeImage.transform = CGAffineTransformIdentity
                })
                
                contentLable.text = "等待奖金"
                
                if oldValue == .Refreshing{
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.tableView?.contentInset.top =  (self.tableView?.contentInset.top)! - HTRefreshControlH
                    })
                }
            }
        }
        
    }
    
    
    var tableView : UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func setupUI(){
        
        backgroundColor = UIColor.yellowColor()
        self.frame.size.height = HTRefreshControlH
        self.frame.origin.y = -HTRefreshControlH
        
        
        addSubview(arroeImage)
        addSubview(contentLable)
        addSubview(indecatorView)
        
        
        arroeImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-45)
            make.centerY.equalTo(self)
        }
        
        contentLable.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arroeImage)
            make.leading.equalTo(arroeImage.snp_trailing)
        }
        
        indecatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arroeImage)
        }
    }
    
    
    func endRefeshing(){
        htState = .Noraml
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        guard let  tableView  = newSuperview  where tableView.isKindOfClass(UIScrollView.self) else {
        
            return
        }
        self.tableView = tableView as? UIScrollView
        self.frame.size.width = tableView.frame.width
        
        
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffset = self.tableView!.contentOffset
        
        let conditionValue = -tableView!.contentInset.top - HTRefreshControlH
        
        //print(contentOffset.y)
        
        if tableView!.dragging {
        
            if contentOffset.y < conditionValue && htState == .Noraml{
                htState = .pulling
                print("控件完全显示")
            }else{
                if contentOffset.y >= conditionValue && htState == .pulling{
                htState = .Noraml
                print("控件没有完全显示")
                }
            }
        }else{
            
            if htState == .pulling {
                htState = .Refreshing
                print("控件刷新中")
            }
        }
    }
    
    
    deinit{
    
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    
    //加载控件
    //加载lable
    private lazy var contentLable : UILabel = {
    
        let  label = UILabel ()
        label.font = UIFont.systemFontOfSize(13)
        label.text = "刷新快会死人的"
        label.textColor = UIColor.blackColor()
        
        return label
    }()
    
    private lazy var arroeImage : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var indecatorView : UIActivityIndicatorView = UIActivityIndicatorView()
    
}
